package org.jks.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;

import org.jks.util.DateUtil;
/**
 * DBUtil 数据库工具类
 * @author turan
 *
 */
public class DBUtil {
	/**
	 * 备份数据库
	 * @param binPath mysql的bin路径
	 * @param username 备份数据库用户名
	 * @param password 备份数据库密码
	 * @param dbname 备份数据库名
	 * @param bakPath 备份路径
	 * @return 如果成功返回true,否则返回false	
	 */
	public static boolean backup(String binPath, String username, String password, String dbname, String bakPath) {
		try {
			Runtime rt = Runtime.getRuntime();
			String params = "";
			if(binPath != null && binPath.trim().length() != 0){
				params += binPath + File.separator;
			}
			params += "mysqldump -u"+username+" -p"+password+" --set-charset=utf8 "+dbname;
			Process child = rt.exec(params);
			InputStream in = child.getInputStream();
			InputStreamReader isr = new InputStreamReader(in, "utf8");
			StringBuffer sb = new StringBuffer("");
			String sql;
			String line;
			BufferedReader br = new BufferedReader(isr);
			while ((line = br.readLine()) != null) {
				sb.append(line + "\r\n");
			}
			sql = sb.toString();
			FileOutputStream fout = new FileOutputStream(bakPath + File.separator + DateUtil.toString(new Date(), "yyyyMMddHHmmss") + ".sql");
			OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
			writer.write(sql);
			writer.flush();
			in.close();
			isr.close();
			br.close();
			writer.close();
			fout.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 恢复数据库
	 * @param binPath mysql的bin路径
	 * @param username 恢复数据库访问用户名
	 * @param password 恢复数据库访问密码
	 * @param dbname 恢复数据库名
	 * @param resPath 恢复sql路径
	 * @return 如果成功返回true,否则返回false
	 */
	public static boolean restore(String binPath, String username, String password, String dbname, String resPath) {
		try {
			Runtime rt = Runtime.getRuntime();
			String params = "";
			if(binPath != null && binPath.trim().length() != 0){
				params += binPath + File.separator;
			}
			params += "mysql -u"+username+" -p"+password+" "+dbname;
			Process child = rt.exec(params);
			OutputStream out = child.getOutputStream();// 控制台的输入信息作为输出流
			String line;
			StringBuffer sb = new StringBuffer("");
			String sql;
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(resPath), "utf8"));
			while ((line = br.readLine()) != null) {
				sb.append(line + "\r\n");
			}
			sql = sb.toString();
			OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
			writer.write(sql);
			writer.flush();
			out.close();
			br.close();
			writer.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
}
